package com.ruibang.glass.quality.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruibang.glass.common.constants.RedisKey;
import com.ruibang.glass.common.domain.file.FileBusiness;
import com.ruibang.glass.quality.constant.QualityErrorCode;
import com.ruibang.glass.quality.domain.req.QualityWarpingReq;
import com.ruibang.glass.quality.domain.req.SemiCheckReportReq;
import com.ruibang.glass.quality.domain.resp.SemiCheckDetailData;
import com.ruibang.glass.quality.domain.resp.WarpingExcelDataResp;
import com.ruibang.glass.quality.entity.QualityThickness;
import com.ruibang.glass.quality.entity.QualityWarping;
import com.ruibang.glass.quality.entity.SpecsConfig;
import com.ruibang.glass.quality.feign.FileApi;
import com.ruibang.glass.quality.mapper.QualityWarpingMapper;
import com.ruibang.glass.quality.service.QualityWarpingService;
import com.ruibang.glass.quality.service.SpecsConfigService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.autoconfigure.redis.RedisSingleService;
import com.teaming.cloud.framework2.common.constant.CommonConstant;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import com.teaming.cloud.framework2.common.pojo.PageRequest;
import com.teaming.cloud.framework2.common.pojo.PageResult;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 半成品翘曲信息 服务实现类
 * </p>
 *
 * @author wujie
 * @since 2024-03-11
 */
@Service
public class QualityWarpingServiceImpl extends ServiceImpl<QualityWarpingMapper, QualityWarping> implements QualityWarpingService {

    private static final String FULL_A_SIDE_WARPING = "整板A面翘曲报告";
    private static final String FULL_B_SIDE_WARPING = "整板B面翘曲报告";

    private static final Integer INT_ELEVEN = 11;

    @Autowired
    private FileApi fileApi;

//    @Autowired
//    private RedisSingleService redisService;

    @Autowired
    private RedisSingleService redisService;

    @Autowired
    private SpecsConfigService specsConfigService;

    @Override
    public void saveInfo(QualityWarping qualityWarping) {
        LocalDateTime now = LocalDateTime.now();
        if(qualityWarping.getTransectTime()==null){
            qualityWarping.setTransectTime(now);
        }
        if(qualityWarping.getRecordTime()==null){
            qualityWarping.setRecordTime(now);
        }
        this.save(qualityWarping);
        //更新文件对应业务Id
        if(CollectionUtils.isNotEmpty(qualityWarping.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setFileIds(qualityWarping.getFileIds());
            fileBusiness.setBusinessId(qualityWarping.getWarpingId());
            fileApi.updateBusinessById(fileBusiness);
        }
    }

    @Override
    public void updateInfo(QualityWarping qualityWarping) {
        //更新文件信息
        if(CollectionUtils.isNotEmpty(qualityWarping.getDeleteFileIds())){
            fileApi.deleteByFileIds(qualityWarping.getDeleteFileIds());
        }
        //新增文件
        if(CollectionUtils.isNotEmpty(qualityWarping.getFileIds())){
            FileBusiness fileBusiness = new FileBusiness();
            fileBusiness.setBusinessId(qualityWarping.getWarpingId());
            fileBusiness.setFileIds(qualityWarping.getFileIds());
            fileApi.updateBusinessById(fileBusiness);
        }

        this.updateById(qualityWarping);
    }

    @Override
    public PageResult<QualityWarping> queryPage(PageRequest<QualityWarpingReq> pageRequest) {
        final QualityWarpingReq param = pageRequest.getParam();
        final LambdaQueryWrapper<QualityWarping> lambda = new QueryWrapper<QualityWarping>().lambda();
        lambda.orderBy(true,false, QualityWarping::getTransectTime);
        this.buildCondition(lambda,param);
        final IPage<QualityWarping> page = this.page(new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize()), lambda);
        if(page!=null&& CollectionUtils.isNotEmpty(page.getRecords())){
            List<String> ids = page.getRecords().stream().map(c->c.getWarpingId()).collect(Collectors.toList());
            ResultBody<List<FileBusiness>> resultBody = fileApi.getFileBusinessByIds(ids);
            Map<String,List<String>> fileMap = null;
            if(resultBody!=null&& CollectionUtils.isNotEmpty(resultBody.getData())){
                fileMap = resultBody.getData().stream().collect(Collectors.toMap(f->f.getBusinessId(), f->f.getFileIds(),(f1, f2)->f1));
            }
            List<SpecsConfig> configs = specsConfigService.getSpecsConfigByIds(page.getRecords().stream().map(qt->qt.getCheckRule()).collect(Collectors.toList()));
            Map<String, SpecsConfig> configMap = null;
            if(CollectionUtils.isNotEmpty(configs)){
                configMap = configs.stream().collect(Collectors.toMap(c->c.getSpecsId(),c->c,(c1,c2)->c1));
            }

            Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
            for (QualityWarping qw : page.getRecords()) {
                if(fileMap!=null){
                    qw.setFileIds(fileMap.get(qw.getWarpingId()));
                }
                if(userMap!=null){
                    qw.setUserName(userMap.get(qw.getUserId())==null?"":userMap.get(qw.getUserId()).toString());
                }
                if(configMap!=null){
                    qw.setSpecsConfig(configMap.get(qw.getCheckRule()));
                }
            }
        }

        PageResult<QualityWarping> pr = new PageResult(page);
        return pr;
    }

    @Override
    public void delete(String id) {
        lambdaUpdate().eq(QualityWarping::getWarpingId, id).set(QualityWarping::getIsDelete, CommonConstant.ONE_STR).update();
    }

    @Override
    public List<QualityWarping> queryQualityWarping(QualityWarpingReq warpingReq) {
        final LambdaQueryWrapper<QualityWarping> lambda = new QueryWrapper<QualityWarping>().lambda();
        this.buildCondition(lambda,warpingReq);
        lambda.orderBy(true,true, QualityWarping::getTransectTime);
        List<QualityWarping> list = this.list(lambda);
        if(CollectionUtils.isNotEmpty(list)){
            Map<Object, Object> userMap = redisService.hmget(RedisKey.USER_GROUP_TYPE);
            for (QualityWarping qw : list) {
                if(userMap!=null){
                    qw.setUserName(userMap.get(qw.getUserId())==null?"":userMap.get(qw.getUserId()).toString());
                }
            }
        }
        return list;
    }

    @Override
    public List<SemiCheckDetailData> queryWarpingCheckData(SemiCheckReportReq warpingReq) {
        return baseMapper.queryWarpingCheckData(warpingReq);
    }

    @Override
    public WarpingExcelDataResp importWarping(List<MultipartFile> files) {
        WarpingExcelDataResp warping = new WarpingExcelDataResp();
        if(CollectionUtils.isNotEmpty(files)){
            for (MultipartFile file : files) {
                InputStream inputStream = null;
                try {
                    inputStream = file.getInputStream();
                    Workbook workbook = WorkbookFactory.create(inputStream);
                    int sheetCount = workbook.getNumberOfSheets();
                    if(sheetCount == CommonConstant.FOUR_INT){
                        Sheet sheet3 = workbook.getSheetAt(CommonConstant.TWO_INT);
                        if(sheet3!=null){
                            Row row0 = sheet3.getRow(CommonConstant.ZERO_INT);
                            Cell cell0 = row0.getCell(CommonConstant.ZERO_INT);
                            String name = cell0.getStringCellValue();
                            if(StringUtils.isNotEmpty(name)){
                                if(name.contains(FULL_A_SIDE_WARPING)){
                                    Row row3 = sheet3.getRow(CommonConstant.THREE_INT);
                                    Cell cell11 = row3.getCell(INT_ELEVEN); //A面翘曲
                                    warping.setASideWarping((float)cell11.getNumericCellValue());
                                }
                            }

                        }

                        Sheet sheet4 = workbook.getSheetAt(CommonConstant.THREE_INT);
                        if(sheet4!=null){
                            Row row0 = sheet4.getRow(CommonConstant.ZERO_INT);
                            Cell cell = row0.getCell(CommonConstant.ZERO_INT);
                            String name = cell.getStringCellValue();
                            if(StringUtils.isNotBlank(name) && name.contains(FULL_B_SIDE_WARPING)){
                                Row row3 = sheet4.getRow(CommonConstant.THREE_INT);
                                Cell cell11 = row3.getCell(INT_ELEVEN); //B面翘曲
                                warping.setBSideWarping((float)cell11.getNumericCellValue());
                            }
                        }
                    }

                } catch (IOException e) {
                    log.error("执行流操作异常:"+e.getMessage());
                    throw new ServiceException(QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getCode(),QualityErrorCode.SEMI_IMPORT_FILE_ERROR.getMsg());
                }
            }

            ResultBody<List<String>> resultBody = fileApi.uploadFiles(files);
            if(resultBody!=null&&CollectionUtils.isNotEmpty(resultBody.getData())){
                warping.setFileIds(resultBody.getData());
            }

        }
        return warping;
    }

    /**
     * 构造查询条件
     * @param lambda
     * @param param
     */
    private void buildCondition(LambdaQueryWrapper<QualityWarping> lambda, QualityWarpingReq param){
        lambda.eq(QualityWarping::getIsDelete, CommonConstant.ZERO_STR);
        if(null == param) return;
        if(StringUtils.isNotBlank(param.getWarpingId())){
            lambda.eq(QualityWarping::getWarpingId, param.getWarpingId());
        }
        if(StringUtils.isNotBlank(param.getProductLine())){
            lambda.eq(QualityWarping::getProductLine, param.getProductLine());
        }
        if(StringUtils.isNotBlank(param.getGlassId())){
            lambda.eq(QualityWarping::getGlassId, param.getGlassId());
        }
        if(StringUtils.isNotBlank(param.getGlassType())){
            lambda.eq(QualityWarping::getGlassType, param.getGlassType());
        }
        if(StringUtils.isNotBlank(param.getGlassModel())){
            lambda.eq(QualityWarping::getGlassModel, param.getGlassModel());
        }
        if(StringUtils.isNotBlank(param.getCheckRule())){
            lambda.eq(QualityWarping::getCheckRule, param.getCheckRule());
        }
        if(StringUtils.isNotBlank(param.getDecide())){
            lambda.eq(QualityWarping::getDecide, param.getDecide());
        }
        if(StringUtils.isNotBlank(param.getUserId())){
            lambda.eq(QualityWarping::getUserId, param.getUserId());
        }

        if(param.getRecordStartTime()!=null&&param.getRecordEndTime()!=null){
            lambda.ge(QualityWarping::getRecordTime, param.getRecordStartTime());
            lambda.le(QualityWarping::getRecordTime, param.getRecordEndTime());
        }
        if(param.getTransectStartTime()!=null&&param.getTransectEndTime()!=null){
            lambda.ge(QualityWarping::getTransectTime, param.getTransectStartTime());
            lambda.le(QualityWarping::getTransectTime, param.getTransectEndTime());
        }

        if(StringUtils.isNotBlank(param.getTeam())){
            lambda.eq(QualityWarping::getTeam, param.getTeam());
        }
        if(StringUtils.isNotBlank(param.getIsRetrospect())){
            lambda.eq(QualityWarping::getIsRetrospect, param.getIsRetrospect());
        }
        if(StringUtils.isNotBlank(param.getRemark())){
            lambda.eq(QualityWarping::getRemark, param.getRemark());
        }

    }
}
